package history.hot100;


import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

// 347. 前 K 个高频元素:https://leetcode-cn.com/problems/top-k-frequent-elements/
// https://leetcode-cn.com/problems/top-k-frequent-elements/solution/qian-k-ge-gao-pin-yuan-su-by-leetcode-solution/
public class LeetCode_347 {
    public static void main(String[] args) {
        int []nums = {4,1,-1,2,-1,2,3};
        topKFrequent(nums, 2);
    }
    public static int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> occurrences = new HashMap<>();
        for (int num: nums) occurrences.put(num, occurrences.getOrDefault(num, 0)+1);

        PriorityQueue<int []> queue = new PriorityQueue<>(new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[1] - o2[1];
            }
        });
        for (Map.Entry<Integer, Integer> entry: occurrences.entrySet()) {
            int num = entry.getKey(), count = entry.getValue();
            if (queue.size()==k) {
                System.out.println(queue.peek()[1]);
                if (queue.peek()[1] < count) {
                    queue.poll();
                    queue.offer(new int[]{num, count});
                }
            } else {
                queue.offer(new int[]{num, count});
            }
        }
        int [] ret = new int[k];
        for (int i = 0; i < k; ++i) {
            ret[i] = queue.poll()[0];
        }
        return ret;
    }
}
